package main

import "fmt"

/**
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:

You must do this in-place without making a copy of the array.
Minimize the total number of operations.

l是nums长度
用i表示当前可以设置非0值的位置
用j做循环变量，当num[j]为0时，设定nums[i]=nums[j],i++
j到达末尾时，位置i之前是非0值，之后(包含位置i)都应该是0值，循环i<l将i及之后位置值设定为0,此题回答完毕
*/

func moveZeroes(nums []int) {
	l := len(nums)
	i, j := 0, 0

	//处理所有非0值，找到0值和非0值的界限位置
	for j < l {
		if nums[j] != 0 {
			nums[i] = nums[j]
			i++
		}
		j++
	}

	// 从i位置开始至末尾，所有值都是0值
	// 所以，只要把 nums[i:] 都置零，即可
	for i < l {
		nums[i] = 0
		i++
	}
}

func main() {
	nums := []int{0, 1, 0, 2}
	moveZeroes(nums)
	fmt.Println(nums)
}
